const db = require('../model/db');

// 创建宠物分类
const createCategory = (req, res) => {
    const { name, description } = req.body;
    
    db.run(
        'INSERT INTO pet_categories (name, description) VALUES (?, ?)',
        [name, description],
        function(err) {
            if (err) {
                return res.status(500).json({ error: '创建宠物分类失败' });
            }
            res.status(201).json({
                id: this.lastID,
                name,
                description
            });
        }
    );
};

// 获取所有宠物分类
const getAllCategories = (req, res) => {
    db.all('SELECT * FROM pet_categories', [], (err, categories) => {
        if (err) {
            return res.status(500).json({ error: '获取宠物分类失败' });
        }
        res.json(categories);
    });
};

// 创建宠物
const createPet = (req, res) => {
    const { name, type, age, price, description } = req.body;
    
    console.log('Received pet data:', { name, type, age, price, description });
    
    if (!name || !type) {
        return res.status(400).json({ error: '宠物名称和类型是必填项' });
    }

    const sql = `INSERT INTO pets (name, type, age, price, description, status) 
                 VALUES (?, ?, ?, ?, ?, 'available')`;
    const params = [name, type, age || null, price || null, description || null];
    
    console.log('Executing SQL:', sql);
    console.log('Parameters:', params);
    
    db.run(sql, params, function(err) {
        if (err) {
            console.error('Database error:', err);
            return res.status(500).json({ error: '创建宠物信息失败' });
        }
        res.status(201).json({
            id: this.lastID,
            name,
            type,
            age,
            price,
            description,
            status: 'available'
        });
    });
};

// 获取所有宠物
const getAllPets = (req, res) => {
    const { status, page = 1, limit = 10 } = req.query;
    let query = 'SELECT * FROM pets';
    let params = [];
    let conditions = [];

    if (status) {
        conditions.push('status = ?');
        params.push(status);
    }

    if (conditions.length > 0) {
        query += ' WHERE ' + conditions.join(' AND ');
    }

    const offset = (page - 1) * limit;
    query += ` LIMIT ? OFFSET ?`;
    params.push(limit, offset);

    db.all(query, params, (err, pets) => {
        if (err) {
            return res.status(500).json({ error: '获取宠物列表失败' });
        }
        
        // 获取总数
        let countQuery = 'SELECT COUNT(*) as total FROM pets';
        if (conditions.length > 0) {
            countQuery += ' WHERE ' + conditions.join(' AND ');
        }
        
        db.get(countQuery, params.slice(0, -2), (err, result) => {
            if (err) {
                return res.status(500).json({ error: '获取宠物总数失败' });
            }
            
            res.json({
                total: result.total,
                page: parseInt(page),
                limit: parseInt(limit),
                data: pets
            });
        });
    });
};

// 获取单个宠物详情
const getPetById = (req, res) => {
    const { id } = req.params;
    
    db.get(
        'SELECT * FROM pets WHERE id = ?',
        [id],
        (err, pet) => {
            if (err) {
                return res.status(500).json({ error: '获取宠物详情失败' });
            }
            if (!pet) {
                return res.status(404).json({ error: '宠物不存在' });
            }
            res.json(pet);
        }
    );
};

// 更新宠物信息
const updatePet = (req, res) => {
    const { id } = req.params;
    const { name, type, age, price, description, status } = req.body;
    
    const updates = [];
    const params = [];
    
    if (name) {
        updates.push('name = ?');
        params.push(name);
    }
    if (type) {
        updates.push('type = ?');
        params.push(type);
    }
    if (age !== undefined) {
        updates.push('age = ?');
        params.push(age);
    }
    if (price !== undefined) {
        updates.push('price = ?');
        params.push(price);
    }
    if (description) {
        updates.push('description = ?');
        params.push(description);
    }
    if (status) {
        updates.push('status = ?');
        params.push(status);
    }
    
    if (updates.length === 0) {
        return res.status(400).json({ error: '没有提供要更新的信息' });
    }
    
    params.push(id);
    const query = `UPDATE pets SET ${updates.join(', ')} WHERE id = ?`;
    
    db.run(query, params, function(err) {
        if (err) {
            return res.status(500).json({ error: '更新宠物信息失败' });
        }
        if (this.changes === 0) {
            return res.status(404).json({ error: '宠物不存在' });
        }
        res.json({ message: '宠物信息更新成功' });
    });
};

// 删除宠物
const deletePet = (req, res) => {
    const { id } = req.params;
    
    db.run('DELETE FROM pets WHERE id = ?', [id], function(err) {
        if (err) {
            return res.status(500).json({ error: '删除宠物失败' });
        }
        if (this.changes === 0) {
            return res.status(404).json({ error: '宠物不存在' });
        }
        res.json({ message: '宠物删除成功' });
    });
};

module.exports = {
    createCategory,
    getAllCategories,
    createPet,
    getAllPets,
    getPetById,
    updatePet,
    deletePet
}; 